package com.example.myproject.service.impl;

import com.example.myproject.dto.like.LikeRequest;
import com.example.myproject.dto.like.LikeResponse;
import com.example.myproject.mapper.CommentLikeMapper;
import com.example.myproject.model.CommentLike;
import com.example.myproject.security.JwtAuthenticationFilter;
import com.example.myproject.service.LikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class LikeServiceImpl implements LikeService {

    @Autowired
    private CommentLikeMapper commentLikeMapper;

    @Override
    @Transactional
    public LikeResponse toggleLike(Integer commentId, LikeRequest req) {
        // 获取当前用户ID（修改这部分）
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Long userId = null;

        if (auth.getPrincipal() instanceof JwtAuthenticationFilter.UserPrincipal) {
            userId = ((JwtAuthenticationFilter.UserPrincipal) auth.getPrincipal()).getId();
        } else {
            throw new IllegalStateException("Unexpected principal type");
        }
        // 检查是否已点赞
        boolean liked = commentLikeMapper.existsByCommentIdAndUserId(Long.valueOf(commentId), userId) > 0;
        
        if ("like".equals(req.getAction())) {
            if (!liked) {
                // 添加点赞记录
                CommentLike like = new CommentLike();
                like.setCommentId(commentId);
                like.setUserId(userId);
                like.setCreateTime(LocalDateTime.now());
                commentLikeMapper.insert(like);
            }
        } else {
            if (liked) {
                // 取消点赞
                commentLikeMapper.deleteByCommentIdAndUserId(Long.valueOf(commentId), userId);
            }
        }
        
        // 更新评论点赞数
        commentLikeMapper.updateCommentLikesCount(Long.valueOf(commentId));
        
        // 获取最新点赞数
        int likesCount = commentLikeMapper.countByCommentId(Long.valueOf(commentId));
        
        // 构建响应
        LikeResponse resp = new LikeResponse();
        resp.setComment_id(commentId);
        resp.setLikes_count(likesCount);
        resp.setUser_liked("like".equals(req.getAction()));
        
        return resp;
    }
}